from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Dict
import json
from demo.interface_parser import InterfaceParser
from fastapi_offline import FastAPIOffline

app = FastAPIOffline()


class MethodDetail(BaseModel):
    method: str
    url: str
    request_body: Dict
    response_body: Dict

class MethodList(BaseModel):
    methods: List[Dict]

parser = InterfaceParser('static/data/interfaces_define.json')

@app.post("/methods", response_model=MethodList)
async def get_methods():
    methods = []
    for interface in parser.interfaces:
        methods.append({
            "method": interface['method'],
            "url": interface['url'],
            "cn_name": interface.get("name", ""),
        })
    return {"methods": methods}

class MethodDetailRequest(BaseModel):
    method: str
    url: str

@app.post("/methods/detail", response_model=MethodDetail)
async def get_method_detail(request: MethodDetailRequest):
    method = request.method
    url = request.url
    for interface in parser.interfaces:
        if interface['method'] == method and interface['url'] == url:
            return {
                "method": method,
                "url": url,
                "cn_name": interface.get("name", ""),
                "request_body": interface.get('request_body', {}),
                "response_body": interface.get('response_body', {})
            }
    return {"error": "Method not found"}

class RequestExampleRequest(BaseModel):
    method: str
    url: str

@app.post("/methods/request_example", response_model=Dict)
async def get_request_example(request: RequestExampleRequest):
    method = request.method
    url = request.url
    request_example = parser.generate_request_example(method, url)
    return request_example

class ResponseExampleRequest(BaseModel):
    method: str
    url: str

@app.post("/methods/response_example", response_model=Dict)
async def get_response_example(request: ResponseExampleRequest):
    method = request.method
    url = request.url
    response_example = parser.generate_response_example(method, url)
    return response_example


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=12346)
